package com.atguigu.zqkJdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Date:2020/8/28
 * Author:ybc
 * Description:
 */
public class ZqkBatchHandlerTest {

    /**
     * 批处理的第一种写法：
     * 每次循环都执行一次SQL语句
     */
    @Test
    public void testBath() {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
          connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhang_s", "root", "123456");
          ps = connection.prepareStatement("insert into t_user (username,password) values (?,?)");
            for (int i = 1; i <= 1000; i++) {
                ps.setObject(1,"user"+i);
                ps.setObject(2,"pwd"+i);
                ps.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                ps.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void testBatchNew(){
        long start  = System.currentTimeMillis();
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhang_s?rewriteBatchedStatements=true", "root", "123456");
            ps = connection.prepareStatement("insert into t_user(username,password) values (?,?)");
            for (int i = 1; i <= 1000; i++) {
                ps.setObject(1,"user"+i);
                ps.setObject(2,"pwd"+i);
                //将sql攒为一批进行处理
                ps.addBatch();
            }
            ps.executeBatch();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时："+(end-start));
    }
}
